package com.zy.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.List;

/**
 * @program: shopping153_cloud
 * @description: 服务器编号分配器
 * @author: zy
 * @create: 2025-08-20 14:16
 */
@Component
public class WorkerIdAssigner {

    // 通过 nacos客户端来获取workerId
    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${spring.application.name}")   //从配置文件中获取服务名,  这样，discoveryClient可以根据服务名取实例列表
    private String serviceName;

    public Long getWorkerId(){
        List<ServiceInstance> instances = discoveryClient.getInstances(   serviceName );
        try {
            String currentIp = InetAddress.getLocalHost().getHostAddress();
            long index = 0;
            for (int i = 0; i < instances.size(); i++) {
                if (instances.get(i).getHost().equals(currentIp)) {
                    index = i;
                    break;
                }
            }
            return index;
        }catch(Exception ex){
            throw new RuntimeException(  "Work Id 分配失败");
        }
    }
}
